#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

import requests
from tqdm import tqdm
import sys
import configparser


def download_file(url, name):
    resp = requests.get(url=url, stream=True)
    # stream=True的作用是仅让响应头被下载，连接保持打开状态，
    # content_size = int(resp.headers['Content-Length']) / 1024  # 确定整个安装包的大小
    with open(name, "wb") as f:
        # print("Total file size: ", content_size, 'k，start downloading...')
        print("Start downloading " + name + " ...")
        for data in tqdm(iterable=resp.iter_content(1024), unit="k", desc=name):
            # 调用iter_content，一块一块的遍历要下载的内容，搭配stream=True，此时才开始真正的下载
            # iterable：可迭代的进度条 total：总的迭代次数 desc：进度条的前缀
            f.write(data)
        print(name + " is downloaded.")


if __name__ == '__main__':
    config = configparser.RawConfigParser()
    config.read(sys.argv[1])

    url = config.get(sys.argv[2], sys.argv[3])
    download_file(url, sys.argv[4])
